package com.nengchuan.kbms.dfs.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.nengchuan.config.exception.NcException;
import com.nengchuan.kbms.dfs.config.PdfConfig;
import com.nengchuan.kbms.dfs.entity.dto.DownloadFileDTO;
import com.nengchuan.kbms.dfs.entity.po.DataFile;
import com.nengchuan.kbms.dfs.util.pdf.ItextPdfUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;

@Service
@Slf4j
public class FdfsServiceImpl implements FdfsService {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private PdfConfig pdfConfig;

    /**
     * 上传文件至 FastDFS 服务
     *
     * @param inputStream 输入流
     * @param fileSize    文件大小
     * @param suffix      扩展名
     * @return
     */
    @Override
    public String uploadFile(InputStream inputStream, long fileSize, String suffix) {
        Objects.requireNonNull(inputStream);
        if (fileSize < 1) {
            throw new NcException("文件大小有误：" + fileSize);
        }

        StorePath sp = storageClient.uploadFile(inputStream, fileSize, suffix, null);
        if (sp == null || StringUtils.isBlank(sp.getFullPath())) {
            throw new NcException("上传文件失败");
        }

        return sp.getFullPath();
    }

    /**
     * 下载文件
     *
     * @param outputStream 输出流
     * @param realFilePath 真实文件路径
     */
    @Override
    public void downloadFile(OutputStream outputStream, String realFilePath) {
        String[] result = resolveRealFilePath(realFilePath);
        String group = result[0];
        String path = result[1];
        try {
            DownloadByteArray callback = new DownloadByteArray();
            byte[] bytes = storageClient.downloadFile(group, path, callback);
            outputStream.write(bytes);
            outputStream.close();
        } catch (IOException e) {
            throw new NcException("下载失败，group: " + group + "，path: " + path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void downloadFile(OutputStream outputStream, DataFile dataFile, DownloadFileDTO downloadFileDTO) {

        String[] result = resolveRealFilePath(dataFile.getRealFilePath());
        String group = result[0];
        String path = result[1];
        try {
            //获取dfs服务器文件数据
            DownloadByteArray callback = new DownloadByteArray();
            byte[] bytes = storageClient.downloadFile(group, path, callback);
            //缓存指定目录
            String filePath = pdfConfig.getPdfPath() + dataFile.getId() + ".pdf";
            //是pdf文件就需要添加水印
            int pointOfIndex = path.lastIndexOf(".");
            String Suffix = path.substring(pointOfIndex + 1);
            if ("pdf".equalsIgnoreCase(Suffix)) {
                //调用这个方法会生成文件,并且添加水印
                ItextPdfUtil.addLostWater(bytes, filePath, downloadFileDTO);
                byte[] byteFromFile = ItextPdfUtil.getByteFromFile(filePath);
                outputStream.write(byteFromFile);
            } else {
                outputStream.write(bytes);
            }
            outputStream.close();

        } catch (IOException e) {
            throw new NcException("下载失败，group: " + group + "，path: " + path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private String[] resolveRealFilePath(String realFilePath) {
        if (StringUtils.isBlank(realFilePath)) {
            throw new NcException("realFilePath不能为空");
        }
        String[] result = new String[2];
        int index = realFilePath.indexOf('/');
        if (index < 0) {
            log.error("fdfs地址解析失败，realFilePath: {}", realFilePath);
        }
        result[0] = realFilePath.substring(0, index);
        result[1] = realFilePath.substring(index + 1);
        return result;
    }

}
